package com.fitc.ui;


import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import javax.swing.*;

import com.fitc.ImageDataWorker;

public class Application extends JFrame {

 private JLabel label;
 private JProgressBar progressBar;
 private JTextArea textArea;
 private JButton  button;
 private ImageDataWorker worker;

 private void initComponents(){
   // The interface will update the text of the UI components
   Informable informable = new Informable(){
     @Override
     public void messageChanged(String message){
       label.setText(message);
       textArea.append(message + "\n");
     }
   };

   // The UI components
   label = new JLabel("");
   add(label, BorderLayout.NORTH);

   textArea = new JTextArea(5, 30);
   add(new JScrollPane(textArea), BorderLayout.CENTER);

   // The cancel button 
   button = new JButton("STOP");
   button.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       // Cancel the worker and wake it up should it be sleeping
       worker.cancel(true);
     }
   });
   add(button, BorderLayout.EAST);

   progressBar = new JProgressBar();
   progressBar.setStringPainted(true);
       add(progressBar, BorderLayout.SOUTH);
                       
   // The worker
   worker = new ImageDataWorker(informable){
     @Override
     protected void done(){
       try {
         int matches = get();
         label.setText("Found: "+matches);

         textArea.append("Done\n");
         textArea.append("Matches Found: "+matches+"\n");

         progressBar.setVisible(false);
       }catch(Exception e){
         JOptionPane.showMessageDialog(Application.this, 
                      "Error", "Search", 
                      JOptionPane.ERROR_MESSAGE);
       }
     }
   };

   // A property listener used to update the progress bar
   PropertyChangeListener listener = 
                              new PropertyChangeListener(){
     public void propertyChange(PropertyChangeEvent event) {
       if ("progress".equals(event.getPropertyName())) {
         progressBar.setValue( (Integer)event.getNewValue() );
       }
     }
   };
   worker.addPropertyChangeListener(listener);
   
   // Start the worker. Note that control is 
   // returned immediately
   worker.execute();
 }

 public static void main(String[] args){
   SwingUtilities.invokeLater(new Runnable(){
     public void run(){
       Application app = new Application();
       app.initComponents();
       app.setDefaultCloseOperation(EXIT_ON_CLOSE);
       app.pack();
       app.setVisible(true);
     }
   });
 }
}
